package com.ziwei.doushu.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.ziwei.doushu.model.BirthInfo;
import com.ziwei.doushu.model.ZiweiResult;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据库帮助类
 */
public class DatabaseHelper extends SQLiteOpenHelper {
    
    private static final String DATABASE_NAME = "ziwei_doushu.db";
    private static final int DATABASE_VERSION = 1;
    
    // 表名
    private static final String TABLE_RESULTS = "results";
    
    // 列名
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_YEAR = "year";
    private static final String COLUMN_MONTH = "month";
    private static final String COLUMN_DAY = "day";
    private static final String COLUMN_HOUR = "hour";
    private static final String COLUMN_IS_MALE = "is_male";
    private static final String COLUMN_PALACE_INFO = "palace_info";
    private static final String COLUMN_STAR_INFO = "star_info";
    private static final String COLUMN_PATTERN_ANALYSIS = "pattern_analysis";
    private static final String COLUMN_FORTUNE_INFO = "fortune_info";
    private static final String COLUMN_CREATE_TIME = "create_time";
    
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    
    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = "CREATE TABLE " + TABLE_RESULTS + " (" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COLUMN_YEAR + " INTEGER NOT NULL, " +
            COLUMN_MONTH + " INTEGER NOT NULL, " +
            COLUMN_DAY + " INTEGER NOT NULL, " +
            COLUMN_HOUR + " INTEGER NOT NULL, " +
            COLUMN_IS_MALE + " INTEGER NOT NULL, " +
            COLUMN_PALACE_INFO + " TEXT, " +
            COLUMN_STAR_INFO + " TEXT, " +
            COLUMN_PATTERN_ANALYSIS + " TEXT, " +
            COLUMN_FORTUNE_INFO + " TEXT, " +
            COLUMN_CREATE_TIME + " DATETIME DEFAULT CURRENT_TIMESTAMP" +
            ")";
        db.execSQL(createTable);
    }
    
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_RESULTS);
        onCreate(db);
    }
    
    /**
     * 保存排盘结果
     */
    public long saveResult(ZiweiResult result) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        
        BirthInfo birthInfo = result.getBirthInfo();
        values.put(COLUMN_YEAR, birthInfo.getYear());
        values.put(COLUMN_MONTH, birthInfo.getMonth());
        values.put(COLUMN_DAY, birthInfo.getDay());
        values.put(COLUMN_HOUR, birthInfo.getHour());
        values.put(COLUMN_IS_MALE, birthInfo.isMale() ? 1 : 0);
        
        // 将复杂对象转换为字符串存储
        values.put(COLUMN_PALACE_INFO, convertMapToString(result.getPalaceInfo()));
        values.put(COLUMN_STAR_INFO, convertMapToString(result.getStarInfo()));
        values.put(COLUMN_PATTERN_ANALYSIS, result.getPatternAnalysis());
        values.put(COLUMN_FORTUNE_INFO, convertListToString(result.getFortuneInfo()));
        
        long id = db.insert(TABLE_RESULTS, null, values);
        db.close();
        return id;
    }
    
    /**
     * 获取所有排盘结果
     */
    public List<ZiweiResult> getAllResults() {
        List<ZiweiResult> results = new ArrayList<>();
        String selectQuery = "SELECT * FROM " + TABLE_RESULTS + " ORDER BY " + COLUMN_CREATE_TIME + " DESC";
        
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        
        if (cursor.moveToFirst()) {
            do {
                ZiweiResult result = createResultFromCursor(cursor);
                results.add(result);
            } while (cursor.moveToNext());
        }
        
        cursor.close();
        db.close();
        return results;
    }
    
    /**
     * 根据ID获取排盘结果
     */
    public ZiweiResult getResultById(long id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_RESULTS, null, COLUMN_ID + "=?", 
            new String[]{String.valueOf(id)}, null, null, null);
        
        ZiweiResult result = null;
        if (cursor.moveToFirst()) {
            result = createResultFromCursor(cursor);
        }
        
        cursor.close();
        db.close();
        return result;
    }
    
    /**
     * 删除排盘结果
     */
    public boolean deleteResult(long id) {
        SQLiteDatabase db = this.getWritableDatabase();
        int result = db.delete(TABLE_RESULTS, COLUMN_ID + "=?", new String[]{String.valueOf(id)});
        db.close();
        return result > 0;
    }
    
    /**
     * 从Cursor创建ZiweiResult对象
     */
    private ZiweiResult createResultFromCursor(Cursor cursor) {
        int yearIndex = cursor.getColumnIndex(COLUMN_YEAR);
        int monthIndex = cursor.getColumnIndex(COLUMN_MONTH);
        int dayIndex = cursor.getColumnIndex(COLUMN_DAY);
        int hourIndex = cursor.getColumnIndex(COLUMN_HOUR);
        int isMaleIndex = cursor.getColumnIndex(COLUMN_IS_MALE);
        int patternIndex = cursor.getColumnIndex(COLUMN_PATTERN_ANALYSIS);
        
        int year = yearIndex >= 0 ? cursor.getInt(yearIndex) : 1990;
        int month = monthIndex >= 0 ? cursor.getInt(monthIndex) : 1;
        int day = dayIndex >= 0 ? cursor.getInt(dayIndex) : 1;
        int hour = hourIndex >= 0 ? cursor.getInt(hourIndex) : 0;
        boolean isMale = isMaleIndex >= 0 ? cursor.getInt(isMaleIndex) == 1 : true;
        
        BirthInfo birthInfo = new BirthInfo(year, month, day, hour, isMale);
        ZiweiResult result = new ZiweiResult(birthInfo);
        
        // 这里需要实现从字符串恢复复杂对象的逻辑
        // 由于简化实现，这里只设置基本信息
        if (patternIndex >= 0) {
            result.setPatternAnalysis(cursor.getString(patternIndex));
        }
        
        return result;
    }
    
    /**
     * 将Map转换为字符串
     */
    private String convertMapToString(java.util.Map<String, String> map) {
        if (map == null) return "";
        StringBuilder sb = new StringBuilder();
        for (java.util.Map.Entry<String, String> entry : map.entrySet()) {
            sb.append(entry.getKey()).append(":").append(entry.getValue()).append(";");
        }
        return sb.toString();
    }
    
    /**
     * 将List转换为字符串
     */
    private String convertListToString(List<String> list) {
        if (list == null) return "";
        StringBuilder sb = new StringBuilder();
        for (String item : list) {
            sb.append(item).append(";");
        }
        return sb.toString();
    }
}
